// AI服务配置
const AI_CONFIG = {
	// 默认超时时间设置为1小时
	timeout: 3600000,
	
	// API接口配置
	apis: {
		deepseek: {
			name: 'DeepSeek',
			url: 'https://api.qster.top/API/v2/DeepSeek',
			parseResponse: (res) => res.data.choices[0].content
		},
		spark: {
			name: '讯飞星火',
			url: 'https://api.52vmy.cn/api/chat/spark',
			parseResponse: (res) => res.data.data.answer
		},
		quark: {
			name: '夸克',
			url: 'https://api.52vmy.cn/api/chat/quark',
			parseResponse: (res) => res.data.data.answer
		},
		yiyan: {
			name: '文心一言',
			url: 'https://api.52vmy.cn/api/chat/yiyan',
			parseResponse: (res) => res.data.data.answer
		}
	}
}

class AiService {
	constructor() {
		this.isProcessing = false
		this.currentApi = 'deepseek' // 默认使用 DeepSeek
	}
	
	// 切换API接口
	switchApi(apiKey) {
		if (AI_CONFIG.apis[apiKey]) {
			this.currentApi = apiKey
			return true
		}
		return false
	}
	
	// 获取当前API配置
	getCurrentApi() {
		return AI_CONFIG.apis[this.currentApi]
	}
	
	// 获取所有可用的API列表
	getAvailableApis() {
		return Object.entries(AI_CONFIG.apis).map(([key, api]) => ({
			key,
			name: api.name
		}))
	}
	
	async sendMessage(message) {
		if (this.isProcessing) return '请等待上一条消息处理完成'
		
		try {
			this.isProcessing = true
			const response = await this.callAiApi(message)
			return response || '抱歉，我现在无法回答，请稍后再试。'
		} catch (error) {
			console.error('AI服务错误:', error)
			return '发生错误，请重试。'
		} finally {
			this.isProcessing = false
		}
	}
	
	async callAiApi(message) {
		const api = this.getCurrentApi()
		
		try {
			const response = await uni.request({
				url: `${api.url}?msg=${encodeURIComponent(message)}`,
				method: 'GET',
				timeout: AI_CONFIG.timeout
			})
			
			if (response.statusCode === 200 && response.data) {
				return api.parseResponse(response)
			}
			
			throw new Error('API请求失败')
		} catch (error) {
			console.error('AI API调用失败:', error)
			throw error
		}
	}
}

export const aiService = new AiService() 